package com.doit.day02;

import com.doit.day01.Util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.*;

public class _01_模拟英雄出场 {
    public static void main(String[] args) throws InterruptedException {
        Jedis jedis = Util.getJedis();
        new Thread(new MyRunnable(jedis)).start();

        Timer timer = new Timer();
        MyTimerTask timerTask = new MyTimerTask(jedis);
        timer.schedule(timerTask,5000,5000);


    }
}

class MyRunnable implements Runnable{
    private Jedis jedis;

    public MyRunnable(Jedis jedis){
        this.jedis = jedis;
    }

    @Override
    public void run() {
        //1.模拟出场
        ArrayList<String> list = new ArrayList<>();
        list.add("瞎子");
        list.add("儿童劫");
        list.add("托儿所");
        list.add("蛮子");
        list.add("女枪");
        list.add("女警");
        list.add("轮子妈");
        list.add("萝莉");
        list.add("艾希");
        list.add("大保健");
        list.add("提莫");
        Random random = new Random();
        //模拟所及出场
        while (true) {
            String hero = list.get(random.nextInt(list.size()));
            //英雄出场了 但是，我要统计出场的次数
            //有两个想法   hash  key heros value (hero,次数)  排序的问题卡主了
            //sorted set
            jedis.zincrby("heros", 1, hero);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MyTimerTask extends TimerTask{
    private Jedis jedis;

    public MyTimerTask(Jedis jedis){
        this.jedis = jedis;
    }

    @Override
    public void run() {
        Set<Tuple> heros = jedis.zrevrangeWithScores("heros", 0, 2);
        for (Tuple hero : heros) {
            double score = hero.getScore();
            String element = hero.getElement();
            System.out.println(element+"=>"+score);
        }
    }
}
